package com.cxh.rmsq.ui.adapter.self

import android.content.Context
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import com.cxh.rmsq.R
import io.rong.imkit.conversation.MessageListAdapter
import io.rong.imlib.model.Conversation
import io.rong.imkit.model.UiMessage
import io.rong.imkit.widget.adapter.IViewProviderListener
import io.rong.imkit.widget.adapter.ViewHolder


class CustomMessageListAdapter(
    listener: IViewProviderListener<UiMessage>, // 必须传递原参数
    private val roleMap: Map<String, String> // 新增参数：用户角色信息
) : MessageListAdapter(listener)  {

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        super.onBindViewHolder(holder, position)
        val uiMessage = getItem(position)
        // 仅处理群组消息
        if (uiMessage?.conversationType == Conversation.ConversationType.GROUP) {
            val senderId = uiMessage.senderUserId
            val roleTag = roleMap[senderId] ?: ""
            // 自定义角色显示逻辑
//            val roleView = holder.itemView.findViewById<TextView>(R.id.tv_role_tag)
//            roleView.text = roleTag
//            roleView.visibility = if (roleTag.isEmpty()) View.GONE else View.VISIBLE
        }
    }

    // 可选：自定义 DiffUtil 逻辑
    override fun setDataCollection(data: List<UiMessage>?) {
        val oldList = ArrayList(mDataList)
        super.setDataCollection(data)
        val diffResult = DiffUtil.calculateDiff(CustomDiffCallback(oldList, data ?: emptyList()))
        diffResult.dispatchUpdatesTo(this)
    }

    private inner class CustomDiffCallback(
        private val oldList: List<UiMessage>,
        private val newList: List<UiMessage>
    ) : DiffUtil.Callback() {
        override fun getOldListSize() = oldList.size
        override fun getNewListSize() = newList.size
        override fun areItemsTheSame(oldPos: Int, newPos: Int) =
            oldList[oldPos].messageId == newList[newPos].messageId
        override fun areContentsTheSame(oldPos: Int, newPos: Int) =
            oldList[oldPos] == newList[newPos] &&
                    roleMap[oldList[oldPos].senderUserId] == roleMap[newList[newPos].senderUserId]
    }

}